﻿using BBCore.Core.Models.Admins;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Components;

namespace BBCore.Server.Components.Pages.Admins
{
    public partial class EditMenu
    {
        private List<TreeViewItem<MenuEntity>> Items { get; set; } = new List<TreeViewItem<MenuEntity>>();

        [Parameter]
        public int RoleId { get; set; }

        [Parameter]
        public List<MenuEntity>? MenuEntities { get; set; }

        [Parameter]
        public Action<List<MenuEntity>>? MenuCallback { get; set; }

        private RoleEntity? RoleEntity { get; set; }

        protected override async Task OnInitializedAsync()
        {
            RoleEntity =  RoleEntity.Where(x => x.Id == RoleId).IncludeMany(x => x.Menus).First();//异步问题
            await base.OnInitializedAsync();
            await RefreshItems();
        }

        private async Task RefreshItems()
        {
            Items.Clear();
            var menus = await MenuEntity.Select.ToListAsync();
            Items.AddRange(CascadingMenu(menus, null));
        }

        private List<TreeViewItem<MenuEntity>> CascadingMenu(List<MenuEntity> menuEntities, TreeViewItem<MenuEntity>? parent) => menuEntities
            .Where(x => x.ParentId == (parent?.Value.Id ?? 0))
            .Select(x =>
            {
                var treeViewItem = new TreeViewItem<MenuEntity>(x) { Text = x.MenuName, Icon = x.Icon, IsExpand = true, Parent = parent };
                treeViewItem.Items = CascadingMenu(menuEntities, treeViewItem);
                if (RoleEntity?.Menus?.Any(y => y.Id == x.Id) == true)
                {
                    treeViewItem.CheckedState = CheckboxState.Checked;
                }
                return treeViewItem;
            })
            .ToList();

        public async Task OnClose(DialogResult result)
        {
            if (result == DialogResult.Yes)
            {
                var menus = new List<MenuEntity>();
                GetMenus(Items.Where(x => x.CheckedState != CheckboxState.UnChecked), menus);
                RoleEntity!.Menus = menus;
                await RoleEntity.SaveManyAsync(nameof(RoleEntity.Menus));
                MenuCallback?.Invoke(menus);
            }
        }

        private void GetMenus(IEnumerable<TreeViewItem<MenuEntity>> treeViewItems, List<MenuEntity> menuEntities)
        {
            menuEntities.AddRange(treeViewItems.Select(x => x.Value));
            foreach (var treeViewItem in treeViewItems)
            {
                if (treeViewItem.Items.Any(x => x.CheckedState != CheckboxState.UnChecked))
                {
                    GetMenus(treeViewItem.Items.Where(x => x.CheckedState != CheckboxState.UnChecked), menuEntities);
                }
            }
        }
    }
}
